<template>
  <div class="xtx-goods-page">
    <div class="container" v-if="loading">
      <div class="loading"></div>
    </div>
    <div class="container" v-else>
      <XtxBread>
        <XtxBreadItem to="/">首页</XtxBreadItem>
        <XtxBreadItem :to="`/category/${goods.categories[1].id}`">{{goods.categories[1].name}}</XtxBreadItem>
        <XtxBreadItem>{{ goods.name }}</XtxBreadItem>
      </XtxBread>
      <!-- 商品容器 -->
      <div class="goods-wrapper">
        <div class="media">
          <!-- 图片预览组件 -->
          <XtxImageView :images="goods.mainPictures"></XtxImageView>
          <!-- 商品销售统计 -->
          <GoodsSales />

        </div>
        <div class="spec">
          <!-- 商品信息 -->
          <GoodsInfo :goods="goods" />
          <!-- sku组件 -->
          <XtxSku :goods="goods" @change="changeSku"></XtxSku>
          <!-- 数量 -->
          <XtxNumbox :min="1" v-model="count" label="数量" />
          <!-- 按钮 -->
          <XtxButton type="primary" style="margin-top: 20px; margin-left: 60px">
            加入购物车
          </XtxButton>
        </div>
      </div>
      <!-- 商品底部 -->
      <GoodsFooter :goods="goods" />
    </div>
  </div>
</template>

<script>
import { onMounted, ref } from 'vue'
import { getGoodsAPI } from '@/api/goods'
import { onBeforeRouteUpdate, useRoute } from 'vue-router'
import GoodsInfo from './component/goods-info.vue'
import GoodsSales from './component/goods-sales.vue'
import GoodsFooter from './component/goods-footer.vue'
export default {
  name: 'xtx-goods-page',
  components: { GoodsInfo, GoodsSales, GoodsFooter },
  setup() {
    const route = useRoute()
    const goods = ref({})
    const loading = ref(true)
    const count = ref(1)
    // 加载数据函数
    const loadData = async id => {
      loading.value = true
      const data = await getGoodsAPI(id)
      goods.value = data.result
      loading.value = false
    }
    // 初始化加载
    onMounted(() => loadData(route.params.id))
    // 将来切换商品加载
    onBeforeRouteUpdate((to, from, next) => {
      loadData(to.params.id)
      next()
    })
    // 选择SKU
    const changeSku = sku => {
      console.log(sku)
    }
    return { goods, loading, changeSku, count }
  }
}
</script>

<style lang="less" scoped>
.loading {
  height: 600px;
  border-top: 72px solid #f5f5f5;
  background: #fff url(../../assets/load.gif) no-repeat center / 80px 80px;
}
.goods-wrapper {
  display: flex;
  background: #fff;
  padding: 40px;
  .media {
    width: 480px;
    margin-right: 40px;
  }
}
</style>  